<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="1200"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog(false)"
  >
    <div v-loading="loading">
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
      >
        基本信息
      </el-row>
      <basic ref="basicRef"></basic>
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
      >
        班组信息
      </el-row>
      <group ref="groupRef" :group-id="groupId" :group-name="groupName" :is-manager="isManager" :corp-role="corpRole">
      </group>
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
      >
        证书信息 <el-button type="primary" @click="handleAddCert">新增证书</el-button>
      </el-row>
      <el-row :gutter="20" justify="center">
        <el-col :span="20">
          <el-tabs v-model="activeName">
            <el-tab-pane label="职业技能证书" :name="1">
              <skills-cert
                :table-data="skillsCertTableData"
                :option-type="optionType"
                @delete-row="handleDeleteRow"
              ></skills-cert>
            </el-tab-pane>
            <el-tab-pane label="执业注册证书" :name="5">
              <registration-cert
                :table-data="registrationCertTableData"
                :option-type="optionType"
                @delete-row="handleDeleteRow"
              ></registration-cert>
            </el-tab-pane>
            <el-tab-pane label="岗位证书" :name="3">
              <job-cert
                :table-data="jobCertTableData"
                :option-type="optionType"
                @delete-row="handleDeleteRow"
              ></job-cert>
            </el-tab-pane>
            <el-tab-pane label="职称证书" :name="4">
              <title-cert
                :table-data="titleCertTableData"
                :option-type="optionType"
                @delete-row="handleDeleteRow"
              ></title-cert>
            </el-tab-pane>
            <el-tab-pane label="安装证书" :name="2">
              <installed-cert
                :table-data="installedCertTableData"
                :option-type="optionType"
                @delete-row="handleDeleteRow"
              ></installed-cert>
            </el-tab-pane>
            <el-tab-pane label="其他证书" :name="6">
              <other-cert
                :table-data="otherCertTableData"
                :option-type="optionType"
                @delete-row="handleDeleteRow"
              ></other-cert>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
    <add-cert :dialog-add-cert="dialogAddCert" @send-close="closeAddCert" @save-info="handleSaveCert"></add-cert>
    <template v-if="optionType != 3" #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import skillsCert from "./components/skillsCert.vue";
import registrationCert from "./components/registrationCert.vue";
import jobCert from "./components/jobCert.vue";
import titleCert from "./components/titleCert.vue";
import installedCert from "./components/installedCert.vue";
import otherCert from "./components/otherCert.vue";
import basic from "./components/basic.vue";
import group from "./components/group.vue";
import addCert from "./addCert.vue";
import { RegisterEmployee, GetEmployeeForm, EditEmployee } from "@/api/worker/index";
import { PersonGroupMemberCreateForm } from "@/api/worker/types";
import { ElButton, ElCol, ElIcon, ElMessage, ElRow, ElText } from "element-plus";
import { CircleCheckFilled } from "@element-plus/icons-vue";

const activeName = ref(1);

const dialogAddCert = ref({
  visible: false,
  title: "新增证书",
  footBtn: "确认新增",
  id: 0,
});

//1：新增 2 修改 3 详情(详情不再使用当前页面)
const optionType = ref(1);

const closeAddCert = () => {
  dialogAddCert.value.visible = false;
};
const handleAddCert = () => {
  dialogAddCert.value.visible = true;
  dialogAddCert.value.id = activeName.value;
  if (activeName.value == 1) dialogAddCert.value.title = "新增职业技能证书";
  if (activeName.value == 2) dialogAddCert.value.title = "新增安装证书";
  if (activeName.value == 3) dialogAddCert.value.title = "新增岗位证书";
  if (activeName.value == 4) dialogAddCert.value.title = "新增职称证书";
  if (activeName.value == 5) dialogAddCert.value.title = "新增执业注册证书";
  if (activeName.value == 6) dialogAddCert.value.title = "新增其他证书";
};
const handleSaveCert = (info: any, type: number) => {
  if (type == 1) {
    skillsCertTableData.value.push(info);
  }
  if (type == 2) {
    installedCertTableData.value.push(info);
  }
  if (type == 3) {
    jobCertTableData.value.push(info);
  }
  if (type == 4) {
    titleCertTableData.value.push(info);
  }
  if (type == 5) {
    registrationCertTableData.value.push(info);
  }
  if (type == 6) {
    otherCertTableData.value.push(info);
  }
};
//声明变量
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
      type: 1,
    }),
  },
  groupId: {
    type: Number,
    default: 0,
  },
  groupName: {
    type: String,
    default: "",
  },
  isManager: {
    type: Boolean,
    default: false,
  },
  corpRole: {
    type: String,
    default: "",
  },
});

const { dialogAddOrEdit, groupId, isManager, groupName, corpRole } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);
const basicRef = ref(ElForm);
const groupRef = ref(ElForm);
const registerEmployeeFormData = reactive<PersonGroupMemberCreateForm>({});
const skillsCertTableData = ref<any[]>([]);
const registrationCertTableData = ref<any[]>([]);
const jobCertTableData = ref<any[]>([]);
const titleCertTableData = ref<any[]>([]);
const installedCertTableData = ref<any[]>([]);
const otherCertTableData = ref<any[]>([]);

const handleDeleteRow = function (type: number, index: number) {
  if (type == 1) {
    skillsCertTableData.value.splice(index, 1);
  } else if (type == 5) {
    registrationCertTableData.value.splice(index, 1);
  } else if (type == 3) {
    jobCertTableData.value.splice(index, 1);
  } else if (type == 4) {
    titleCertTableData.value.splice(index, 1);
  } else if (type == 2) {
    installedCertTableData.value.splice(index, 1);
  } else if (type == 6) {
    otherCertTableData.value.splice(index, 1);
  }
};

const initForm = async function () {
  optionType.value = dialogAddOrEdit.value.type;
  if (dialogAddOrEdit.value.id) {
    loading.value = true;
    let res = await GetEmployeeForm(dialogAddOrEdit.value.id);
    loading.value = false;
    if (res.type === 0) {
      if (res.success) {
        basicRef.value.initForm(res.data.person, optionType.value);
        if (res.data.bank) {
          res.data.member.bankName = res.data.bank.bankName;
          res.data.member.cardNo = res.data.bank.cardNo;
        }
        groupRef.value.initForm(res.data.member, optionType.value);
        if (res.data.certificates && res.data.certificates.length > 0) {
          skillsCertTableData.value = res.data.certificates.filter((item: any) => {
            return item.certificateType == 1;
          });
          registrationCertTableData.value = res.data.certificates.filter((item: any) => {
            return item.certificateType == 5;
          });
          jobCertTableData.value = res.data.certificates.filter((item: any) => {
            return item.certificateType == 3;
          });
          titleCertTableData.value = res.data.certificates.filter((item: any) => {
            return item.certificateType == 4;
          });
          installedCertTableData.value = res.data.certificates.filter((item: any) => {
            return item.certificateType == 2;
          });
          otherCertTableData.value = res.data.certificates.filter((item: any) => {
            return item.certificateType == 6;
          });
        }
      } else {
      }
    } else {
    }
  }
};
const handleKeyDownSubmit = (event: { keyCode: number }) => {
  if (event.keyCode == 13) {
    // 在这里执行要触发的逻辑
    handleSubmit();
  }
};
// const handleKeyDownElMessageBox = (event: { keyCode: number }) => {
//   if (event.keyCode == 13) {
//     // 在这里执行要触发的逻辑
//     console.log("执行回车")
//     closeElmessageBox(true);
//   }
// };
onMounted(() => {
  initForm();
  // 添加键盘事件监听
  document.removeEventListener("keydown", handleKeyDownSubmit);
  document.addEventListener("keydown", handleKeyDownSubmit);
});

// 在组件卸载时移除事件监听
onBeforeUnmount(() => {
  document.removeEventListener("keydown", handleKeyDownSubmit);
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean, workerInfo?: any) {
  emit("sendClose", needRefresh, workerInfo);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  basicRef.value.resetForm();
  groupRef.value.resetForm();
  skillsCertTableData.value = [];
  registrationCertTableData.value = [];
  jobCertTableData.value = [];
  titleCertTableData.value = [];
  installedCertTableData.value = [];
  otherCertTableData.value = [];
}

const closeElmessageBox = (needReset?: boolean) => {
  if (document.getElementsByClassName("el-message-box__close").length > 0) {
    document.getElementsByClassName("el-message-box__close")[0]?.click();
  }
  console.log(needReset);
  if (needReset) {
    console.log("重置表单");
    resetForm();
  }
};

/**
 * 项目表单提交
 */
const handleSubmit = async () => {
  let basicValid = await basicRef.value.validation();
  let groupValid = await groupRef.value.validation();
  if (!basicValid || !groupValid) {
    return;
  }
  registerEmployeeFormData.person = basicRef.value.formData;
  registerEmployeeFormData.bank = groupRef.value.formData;
  registerEmployeeFormData.member = groupRef.value.formData;
  if (!registerEmployeeFormData.certificates) {
    registerEmployeeFormData.certificates = [];
  }
  registerEmployeeFormData.certificates = skillsCertTableData.value.concat(
    registrationCertTableData.value,
    jobCertTableData.value,
    titleCertTableData.value,
    installedCertTableData.value,
    otherCertTableData.value
  );
  registerEmployeeFormData.certificates.forEach((item: any) => {
    item.holder = registerEmployeeFormData.person.name;
  });
  document.removeEventListener("keydown", handleKeyDownSubmit);
  loading.value = true;
  if (optionType.value === 2) {
    // console.log("memberId",registerEmployeeFormData.member.id);
    EditEmployee(registerEmployeeFormData.member.id, registerEmployeeFormData)
      .then((res: any) => {
        if (res.success === true) {
          ElMessage.success(res.msg);
          closeDialog(true);
        } else {
          // closeDialog(true);
        }
      })
      .finally(() => {
        loading.value = false;
        setTimeout(() => {
          document.removeEventListener("keydown", handleKeyDownSubmit);
          document.addEventListener("keydown", handleKeyDownSubmit);
        }, 200);
      });
  } else {
    RegisterEmployee(registerEmployeeFormData)
      .then(async (res: any) => {
        if (res.type != 0 || !res.success) {
          setTimeout(() => {
            document.removeEventListener("keydown", handleKeyDownSubmit);
            document.addEventListener("keydown", handleKeyDownSubmit);
          }, 200);
          loading.value = false;
          return;
        }
        basicRef.value.saveCacheForm();
        groupRef.value.saveCacheForm();
        // document.addEventListener("keydown", handleKeyDownElMessageBox);
        await ElMessageBox({
          title: "提示",
          showConfirmButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          // distinguishCancelAndClose: true,
          message: () =>
            h("div", [
              h(ElRow, [
                h(
                  ElCol,
                  {
                    style: {
                      paddingLeft: "10%",
                    },
                  },
                  [
                    h(ElText, { type: "success" }, [
                      h(
                        ElIcon,
                        {
                          size: 20,
                          style: {
                            verticalAlign: "middle",
                          },
                        },
                        [h(CircleCheckFilled)]
                      ),
                    ]),
                    h(
                      ElText,
                      {
                        style: {
                          fontSize: "16px",
                          paddingLeft: "10px",
                        },
                      },
                      ["新增成功,是否添加合同信息!"]
                    ),
                  ]
                ),
              ]),
              h(ElRow, { style: "margin-top: 10px" }, [
                h(
                  ElCol,
                  {
                    align: "right",
                  },
                  [
                    h(
                      ElButton,
                      {
                        onClick(event: any) {
                          if (event.pointerType != "mouse") {
                            return;
                          }
                          ElMessageBox.close();
                          closeDialog(true);
                        },
                      },
                      ["取消"]
                    ),
                    h(
                      ElButton,
                      {
                        type: "primary",
                        plain: true,
                        onClick(event: any) {
                          if (event.pointerType != "mouse") {
                            return;
                          }
                          closeElmessageBox(true);
                        },
                      },
                      ["继续添加工人信息"]
                    ),
                    h(
                      ElButton,
                      {
                        type: "primary",
                        onClick(event: any) {
                          if (event.pointerType != "mouse") {
                            return;
                          }
                          ElMessageBox.close();
                          closeDialog(true, res.data);
                        },
                      },
                      ["新增合同"]
                    ),
                  ]
                ),
              ]),
            ]),
          beforeClose(action, instance, done) {
            console.log(action);
            if (action == "cancel") {
              document.removeEventListener("keydown", handleKeyDownSubmit);
              document.addEventListener("keydown", handleKeyDownSubmit);
              resetForm();
              loading.value = false;
              done();
            }
          },
        });
      })
      .catch(() => {
        setTimeout(() => {
          document.removeEventListener("keydown", handleKeyDownSubmit);
          document.addEventListener("keydown", handleKeyDownSubmit);
        }, 200);
        loading.value = false;
      });
  }
};
</script>

<style lang="scss" scoped>
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
